import http from 'http';
import { Headers, HeaderValue } from './exchange';

export type ResponseBody = string | Buffer | undefined | null; // TODO: 支持更多类型

export interface Response {
  statusCode: number;
  body: ResponseBody;
  headers: Headers;
  setHeader(name: string, value: HeaderValue): void;
  readonly res: http.ServerResponse;
}

export class HttpResponse implements Response {
  #res: http.ServerResponse;
  #body: ResponseBody;
  #headers: Headers;
  constructor(res: http.ServerResponse) {
    this.#res = res;
  }

  get statusCode(): number {
    return this.#res.statusCode;
  }

  set statusCode(code: number) {
    this.#res.statusCode = code;
  }

  get body(): ResponseBody {
    return this.#body;
  }

  set body(b: ResponseBody) {
    this.#body = b;
  }

  get headers(): Headers {
    return this.#res.getHeaders() as Headers;
  }

  set headers(hs: Headers) {
    if (hs) {
      for (const name in hs) {
        if (Object.prototype.hasOwnProperty.call(hs, name)) {
          const value = hs[name];
          if (value) {
            this.setHeader(name, value);
          }
        }
      }
    }
  }

  get res(): http.ServerResponse {
    return this.#res;
  }

  setHeader(name: string, value: HeaderValue): void {
    this.#res.setHeader(name, value);
  }
}
